package setting

import (
	"../common"
	"../web"
	"strconv"
	"strings"
)

type SetTestingObj struct {
	common.BaseHandler
}

func (self *SetTestingObj) Prepare() {
	stations := *common.FetchAllRowsPtr(
		`SELECT STATION, ''
           FROM SFC_STATION(NOLOCK) 
          ORDER BY STATION`,
		self.Usr.Conn, new(common.Station))

	items := *common.FetchAllRowsPtr(
		`SELECT ITEM, ISNULL(DESCRIP,'') 
           FROM SFC_ITEMS(NOLOCK) 
          ORDER BY ITEM`,
		self.Usr.Conn, new(common.ItemDesc))

	self.TmplData["stations"] = stations
	self.TmplData["items"] = items
}

func (self *SetTestingObj) ParameterCheck() bool {
	c_item := self.Ctx.Params["item"]
	c_stat := self.Ctx.Params["station"]
	c_tnum := strings.TrimSpace(self.Ctx.Params["times"])
	if c_item == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please select the item.")
		return false
	}
	if c_stat == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please select the Station.")
		return false
	}
	i_qty, err := strconv.Atoi(c_tnum)
	if err != nil {
		self.TmplData["error"] = common.GetText(self.Lang, "Test times must be a numeric.")
		return false
	}
	if i_qty < 1 {
		self.TmplData["error"] = common.GetText(self.Lang, "Qty must be more than zero.")
		return false
	}

	self.Sqlparas = append(self.Sqlparas, c_item)
	self.Sqlparas = append(self.Sqlparas, c_stat)
	self.Sqlparas = append(self.Sqlparas, i_qty)
	self.Sqlparas = append(self.Sqlparas, self.Usr.Username)
	self.Flashparas = []interface{}{c_stat}

	return true
}

func (self *SetTestingObj) SqlExecute() bool {
	spRtnData := *common.FetchOneRowPtr(
		`sp_SetTesting ?, ?, ?, ?`,
		self.Usr.Conn, new(common.SPReturn), self.Sqlparas...)
	if spRtnData.(common.SPReturn).Flag > 0 {
		self.TmplData["error"] = common.GetTextSP(self.Lang, spRtnData)
		return false
	}
	return true
}

func TestingSetHandler(ctx *web.Context) {
	self := new(SetTestingObj)
	self.Ctx = ctx
	self.Url = "/settest"
	self.Html = "settest.html"
	self.Rightlist = []string{"settest"}
	self.Flashstr = "Set Station: [ %v ] Testing times finished."
	self.Do(self)
}
